import pandas as pd
import time

def connect_string(x, ms):
    x = list(map(lambda i: sorted(i.split(ms)), x))
    all = len(x[0])
    r = []
    for i in range(len(x)):
        for j in range(i, len(x)):
            if x[i][:all -1] == x[j][: all - 1] and x[i][all - 1] != x[j][all - 1]:
                r.append(x[i][:all - 1] + sorted([x[j][all - 1], x[i][all -1]]))
    return r


def find_rule(d, support, confidence, ms=u'-->'):
    result = pd.DataFrame(index=['support', 'confidence'])

    support_series = 1.0 * d.sum() / len(d)
    column = list(support_series[support_series> support].index)
    k = 0

    while len(column) > 1 :
        k = k + 1
        print("Search num: " + str(k))
        column = connect_string(column, ms)
        print("All numbers: " + str(len(column)))
        sf = lambda  i: d[i].prod(axis=1, numeric_only=True)

        d_2 = pd.DataFrame(list(map(sf, column)), index=[ms.join(i) for i in column]).T

        support_series_2 = 1.0 * d_2[[ms.join(i) for i in column]].sum() / len(d)
        column = list(support_series_2[support_series_2 > support].index)
        support_series = support_series.append(support_series_2)
        column2 = []

        for col in column:
            col = col.split(ms)
            for j in range(len(col)):
                column2.append(col[:j] + col[j + 1:] + col[j:j + 1])

        cofidence_series = pd.Series(index=[ms.join(i) for i in column2])

        for col in column2:
            cofidence_series[ms.join(col)] = support_series[ms.join(sorted(col))] / support_series[ms.join(col[:len(col) - 1])]

        for i in cofidence_series[cofidence_series > confidence].index:
            result[i] = 0.0
            result[i]['confidence'] = cofidence_series[i]
            result[i]['support'] = support_series[ms.join(sorted(i.split(ms)))]

    result = result.T.sort_values(['confidence', 'support'], ascending=False)
    print("Result: ")
    print(result)

    return result

def testApriori():
    pFile = "E:/csdn/chaoshi.xls"
    dframe = pd.read_excel(pFile)
    dframe = dframe.replace('T', 1)
    dframe = dframe.replace('F', 0)
    # dframe = dframe.replace(0, 'F')
    print(dframe)

    find_rule(dframe, 0.3, 0.7)

def testFPtree():
    pFile = "E:/csdn/chaoshi.xls"
    dframe = pd.read_excel(pFile)
    headLst = dframe.columns.values.tolist()
    print(headLst)
    print(headLst[3])
    arr = dframe.values
    print(dframe.shape[0])
    print(len(arr), arr[0])
    print(list(arr[7]))
    dataLst = []
    cols = len(headLst)
    for row in range(dframe.shape[0]):
        rowLst = []
        for col in range(cols):
            if arr[row][col] == 'T':
                rowLst.append(headLst[col])
        dataLst.append(rowLst)

    for i in range(10):
        print(dataLst[i])

if __name__ == '__main__':
    timeStart = time.time()
    testApriori()
    timeEnd = time.time()
    print("Time: " + str(timeEnd - timeStart) + " sec.")
    # testFPtree()